<?php
// Version: 1.3c; Groups

if (!defined('SMF'))
	die('Hacking attempt...');

function GroupMods()
{
	isAllowedTo('view_groups');

	loadTemplate('Groups');

	loadLanguage('Groups');
	loadLanguage('Admin');

	$subActions = array(
		'members' => 'ViewGroup'
	);

	if (isset($_REQUEST['sa']) && isset($subActions[$_REQUEST['sa']]))
	{
		$sa = $subActions[$_REQUEST['sa']];
		unset($subActions);

		$sa();
	}
	else
		GroupModsIndex();
}

function GroupModsIndex()
{
	global $db_prefix, $txt, $scripturl, $context, $settings, $ID_MEMBER;
	
	$query =db_query("
		SELECT mg.ID_GROUP
		FROM ({$db_prefix}membergroups AS mg)
			LEFT JOIN {$db_prefix}members AS mem ON (mem.ID_GROUP = mg.ID_GROUP OR FIND_IN_SET(mg.ID_GROUP, mem.additionalGroups))
			LEFT JOIN {$db_prefix}group_moderators as mods ON (mg.ID_GROUP = mods.ID_GROUP)
		WHERE (mem.ID_MEMBER = $ID_MEMBER OR mods.ID_MEMBER = $ID_MEMBER)
		ORDER BY mg.groupName", __FILE__, __LINE__);
	
	$groups = array();
	while ($row = mysql_fetch_assoc($query))	
		$groups[] = $row['ID_GROUP'];
	mysql_free_result($query);
	
	$query = db_query("
		SELECT mg.ID_GROUP, mg.groupName, mg.minPosts, mg.onlineColor, mg.stars, mods.ID_MEMBER as modID, mm.realName as modName
		FROM ({$db_prefix}membergroups AS mg)
			LEFT JOIN {$db_prefix}group_moderators as mods ON (mg.ID_GROUP = mods.ID_GROUP)
			LEFT JOIN {$db_prefix}members AS mm ON (mods.ID_MEMBER = mm.ID_MEMBER)
		WHERE FIND_IN_SET(mg.ID_GROUP,'".implode(",",$groups)."')
		ORDER BY mg.groupName", __FILE__, __LINE__);
	
	$context['groups'] = array(
		'regular' => array(),
		'post' => array()
	);
	while ($row = mysql_fetch_assoc($query))
	{
		$row['stars'] = explode('#', $row['stars']);
		if (! isset($context['groups']['regular'][$row['ID_GROUP']])) 
			$context['groups']['regular'][$row['ID_GROUP']] = array(
			'id' => $row['ID_GROUP'],
			'name' => $row['groupName'],
			'moderators' => array(), //inserted later
			'allow_delete' => $row['ID_GROUP'] > 4,
			'can_search' => $row['ID_GROUP'] != 3,
			'href' => $scripturl . '?action=groups;sa=members;id=' . $row['ID_GROUP'],
			'link' => '<a href="' . $scripturl . '?action=groups;sa=members;id=' . $row['ID_GROUP'] . '">' . $row['groupName'] . '</a>',
			'is_post_group' => $row['minPosts'] != -1,
			'min_posts' => $row['minPosts'] == -1 ? '-' : $row['minPosts'],
			'color' => empty($row['onlineColor']) ? '' : $row['onlineColor'],
			'stars' => !empty($row['stars'][0]) && !empty($row['stars'][1]) ? str_repeat('<img src="' . $settings['images_url'] . '/' . $row['stars'][1] . '" alt="*" border="0" />', $row['stars'][0]) : '',
			'last_group' => false
		);
		//set moderators
		$context['groups']['regular'][$row['ID_GROUP']]['moderators'][] = 
			'<a href="' . $scripturl . '?action=profile;u=' . $row['modID'] . '">' . $row['modName'] . '</a>';
	}
	mysql_free_result($query);

	$request = db_query("
		SELECT COUNT(ID_MEMBER)
		FROM {$db_prefix}members
		WHERE ID_GROUP = 0", __FILE__, __LINE__);
	list ($num_members) = mysql_fetch_row($request);
	mysql_free_result($request);

	$context['groups'][count($context['groups']) - 1]['last_group'] = true;

	$context['page_title'] = $txt['groups_title'];
	$context['linktree'][] = array(
		'url' => $scripturl . '?action=groups',
		'name' => $txt['groups_title']
	);

}

// Display members of a group, and allow adding of members to a group. Silly function name though ;)
function ViewGroup()
{
	global $txt, $scripturl, $db_prefix, $context, $modSettings, $ID_MEMBER;

	$_REQUEST['id'] = (int) $_REQUEST['id'];

	$request = db_query("
		SELECT id_group
		FROM {$db_prefix}group_moderators
		WHERE ID_MEMBER = $ID_MEMBER AND id_group = $_REQUEST[id]", __FILE__, __LINE__);

	$context['no_group_moderator'] = (mysql_num_rows($request) == 0) ;
		
	mysql_free_result($request);

	// Start!
	$context['start'] = isset($_REQUEST['start']) ? (int) $_REQUEST['start'] : 0;

	// Load up the group details - and ensure this ISN'T a post group ;)
	$request = db_query("
		SELECT ID_GROUP AS id, groupName AS name, minPosts = -1 AS assignable, GroupModOptions AS options
		FROM {$db_prefix}membergroups
		WHERE ID_GROUP = $_REQUEST[id]
		LIMIT 1", __FILE__, __LINE__);
	// Not really possible...
	if (mysql_num_rows($request) == 0)
		fatal_lang_error(1);
	$context['group'] = mysql_fetch_assoc($request);
	mysql_free_result($request);

	if ($context['group']['id'] == 1 && !allowedTo('admin_forum'))
		$context['group']['assignable'] = 0;
	
	// Changing members in this group?
	if (isset($_POST['sc']) &&  $context['group']['assignable'] && $_REQUEST['id'] != 3)
	{
		if ($context['no_group_moderator'])
			fatal_error($txt['not_groupmod _error'], false);

		checkSession();

		// Removing member from group?
		if (isset($_POST['remove']) && isset($_REQUEST['rem']))
		{
			$members = array();
			foreach ($_REQUEST['rem'] AS $remove => $dummy)
				$members[] = (int) $remove;

			// First, reset those who have this as their primary group - this is the easy one.
			db_query("
				UPDATE {$db_prefix}members
				SET ID_GROUP = 0
				WHERE ID_GROUP = $_REQUEST[id]
					AND ID_MEMBER IN (" . implode(', ', $members) . ")
				LIMIT " . count($members), __FILE__, __LINE__);

			// Those who have it as part of their additional group must be updated the long way... sadly.
			$request = db_query("
				SELECT ID_MEMBER, additionalGroups
				FROM {$db_prefix}members
				WHERE FIND_IN_SET($_REQUEST[id], additionalGroups)
					AND ID_MEMBER IN (" . implode(', ', $members) . ")
				LIMIT " . count($members), __FILE__, __LINE__);
			while ($row = mysql_fetch_assoc($request))
			{
				$tempGroup = array_flip(explode(',', $row['additionalGroups']));
				unset($tempGroup[$_REQUEST['id']]);
				$tempGroup = implode(',', array_flip($tempGroup));

				// Do the update for this member - this may be slow for lots of people... but how many you really do at once?
				db_query("
					UPDATE {$db_prefix}members
					SET additionalGroups = '$tempGroup'
					WHERE ID_MEMBER = $row[ID_MEMBER]
					LIMIT 1", __FILE__, __LINE__);
			}
			mysql_free_result($request);
		}
		// Must be adding...
		elseif (isset($_REQUEST['add']) && !empty($_REQUEST['toAdd']))
		{
			// Get all the members to be added... taking into account names can be quoted ;)
			$_REQUEST['toAdd'] = strtr(un_htmlspecialchars($_REQUEST['toAdd']), array('\\"' => '"'));

			preg_match_all('~"([^"]+)"~', $_REQUEST['toAdd'], $matches);
			$memberQuery = array_unique(array_merge($matches[1], explode(',', preg_replace('~"([^"]+)"~', '', $_REQUEST['toAdd']))));

			foreach ($memberQuery as $index => $member)
			{
				if (strlen(trim($member)) > 0)
					$memberQuery[$index] = strtolower(trim($member));
				else
					unset($memberQuery[$index]);
			}

			$request = db_query("
				SELECT ID_MEMBER, ID_GROUP, additionalGroups
				FROM {$db_prefix}members
				WHERE memberName IN ('" . implode("', '", $memberQuery) . "')", __FILE__, __LINE__);

			// Reset the query array and we'll use it to update the members.
			$memberQuery = array(
				'main_group' => array(),
				'additional' => array()
			);

			while ($row = mysql_fetch_assoc($request))
			{
				// Verify that they are not already a member - and add them to our array.
				if ($row['ID_GROUP'] != $_REQUEST['id'] && !in_array($_REQUEST['id'], explode(',', $row['additionalGroups'])))
					$memberQuery[$row['ID_GROUP'] == 0 && substr_count($context['group']['options'], 'P') == 1 ? 'main_group' : 'additional'][] = $row['ID_MEMBER'];
			}
			mysql_free_result($request);

			// Do the updates...
			if (!empty($memberQuery['main_group']))
				db_query("
					UPDATE {$db_prefix}members
					SET ID_GROUP = $_REQUEST[id]
					WHERE ID_MEMBER IN (" . implode(', ', $memberQuery['main_group']) . ")
					LIMIT " . count($memberQuery['main_group']), __FILE__, __LINE__);

			// This one is more complicated!
			if (!empty($memberQuery['additional']))
			{
				db_query("
					UPDATE {$db_prefix}members
					SET additionalGroups = IF(additionalGroups = '', '$_REQUEST[id]', CONCAT(additionalGroups, ',$_REQUEST[id]'))
					WHERE ID_MEMBER IN (" . implode(', ', $memberQuery['additional']) . ")
					LIMIT " . count($memberQuery['additional']), __FILE__, __LINE__);
			}
		}
	}
	// Sort out the sorting!
	$sort_methods = array(
		'name' => 'realName',
		'active' => 'lastLogin',
		'registered' => 'dateRegistered',
		'posts' => 'posts',
	);

	// They didn't pick one, default to by name..
	if (!isset($_REQUEST['sort']) || !isset($sort_methods[$_REQUEST['sort']]))
	{
		$context['sort_by'] = 'name';
		$querySort = 'realName';
	}
	// Otherwise default to ascending.
	else
	{
		$context['sort_by'] = $_REQUEST['sort'];
		$querySort = $sort_methods[$_REQUEST['sort']];
	}

	$context['sort_direction'] = isset($_REQUEST['desc']) ? 'down' : 'up';

	// Count members of the group.
	$request = db_query("
		SELECT COUNT(ID_MEMBER)
		FROM {$db_prefix}members
		WHERE " . ($context['group']['assignable'] ? "ID_GROUP = $_REQUEST[id] OR FIND_IN_SET($_REQUEST[id], additionalGroups)" : "ID_POST_GROUP = $_REQUEST[id]"), __FILE__, __LINE__);
	list ($context['total_members']) = mysql_fetch_row($request);
	mysql_free_result($request);

	// Create the page index.
	$context['page_index'] = constructPageIndex($scripturl . '?action=groups;sa=members;id=' . $_REQUEST['id'] . ';sort=' . $context['sort_by'] . (isset($_REQUEST['desc']) ? ';desc' : ''), $context['start'], $context['total_members'], $modSettings['defaultMaxMembers']);

	// Load up all members of this group.
	$request = db_query("
		SELECT ID_MEMBER, realName, memberName, emailAddress, memberIP, dateRegistered, lastLogin, posts
		FROM {$db_prefix}members
		WHERE " . ($context['group']['assignable'] ? "ID_GROUP = $_REQUEST[id] OR FIND_IN_SET($_REQUEST[id], additionalGroups)" : "ID_POST_GROUP = $_REQUEST[id]") . "
		ORDER BY $querySort " . ($context['sort_direction'] == 'down' ? 'DESC' : 'ASC') . "
		LIMIT $context[start], $modSettings[defaultMaxMembers]", __FILE__, __LINE__);
	$context['members'] = array();
	while ($row = mysql_fetch_assoc($request))
		$context['members'][] = array(
			'id' => $row['ID_MEMBER'],
			'name' => '<a href="' . $scripturl . '?action=profile;u=' . $row['ID_MEMBER'] . '">' . $row['realName'] . '</a>',
			'ip' => '<a href="' . $scripturl . '?action=trackip;searchip=' . $row['memberIP'] . '">' . $row['memberIP'] . '</a>',
			'registered' => timeformat($row['dateRegistered']),
			'last_online' => empty($row['lastLogin']) ? $txt['never'] : timeformat($row['lastLogin']),
			'posts' => $row['posts'],
		);
	mysql_free_result($request);

	// Select the template.
	$context['sub_template'] = 'group_members';
	$context['page_title'] = $txt['groups_members_title'] . ': ' . $context['group']['name'];
	$context['linktree'][] = array(
		'url' => $scripturl . '?action=groups',
		'name' => $txt['groups_title']
	);
	$context['linktree'][] = array(
		'url' => $scripturl . '?action=groups;sa=members;id=' . $_REQUEST['id'],
		'name' => $context['group']['name']
	);
}

// Insert a list of moderators into the database
function insertGroupMods($moderator_string, $boardID)
{
	global $db_prefix;

	// Divvy out the usernames, remove extra space.
	$moderator_string = strtr($moderator_string, array('\\"' => '"'));

	preg_match_all('~"([^"]+)"~', strtr($moderator_string, array('\\"' => '"')), $matches);
	$moderators = array_merge($matches[1], explode(',', preg_replace('~"([^"]+)"~', '', $moderator_string)));

	for ($k = 0, $n = count($moderators); $k < $n; $k++)
	{
		$moderators[$k] = trim($moderators[$k]);

		if (strlen($moderators[$k]) == 0)
			unset($moderators[$k]);
	}

	// Find all the ID_MEMBERs for the memberName's in the list.
	if (empty($moderators))
		return;

	$result = db_query("
		SELECT ID_MEMBER
		FROM {$db_prefix}members
		WHERE memberName IN ('" . implode("','", $moderators) . "')
		LIMIT " . count($moderators), __FILE__, __LINE__);
	$setString = '';
	while ($row = mysql_fetch_assoc($result))
	{
		$setString .= "
				($boardID, $row[ID_MEMBER]),";
	}

	if (!empty($setString))
	{
		db_query("
			INSERT INTO {$db_prefix}group_moderators
				(id_group, ID_MEMBER)
			VALUES" . substr($setString, 0, -1), __FILE__, __LINE__);
	}

	mysql_free_result($result);
}

?>
